﻿using System;
using System.Collections.Generic;
using System.Text;
using IotS.Core.Helpers;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace IotS.MessageService
{
    public class MessageListener : IService
    {
        private readonly MSSettings _settings;
        private readonly QueueSub _sub;

        public MessageListener()
        {
            _sub = new QueueSub(true);
            _settings = Program.Configuration.Get<MSSettings>();
        }

        public void Start()
        {
            try
            {
                Console.Write("Start Listener ");
                _sub.Start(TranslateMessage);
                Console.WriteLine(". OK!");
            }
            catch (Exception e)
            {
                Console.Write("Failed!");
                Console.WriteLine(e);
            }
        }

        private void TranslateMessage(string s)
        {
            var message = JsonConvert.DeserializeObject<Message>(s);

            Console.WriteLine($"topic: {message.Topic} inTopic {_settings.Mqtt.Topic}");
            if (message.Topic == _settings.Mqtt.HeartTopic)
            {
                RedisHelper.Set(_settings.Mqtt.HeartTopic, message.Payload, TimeSpan.FromMinutes(5));
            }
            else if (message.Topic == _settings.Mqtt.Topic)
            {
                var msgs = message.Payload.Split('#');
                if (msgs.Length == 2)
                {
                    Console.WriteLine($"set {msgs[0]} value {msgs[1]}");
                    RedisHelper.Set(msgs[0], msgs[1], TimeSpan.FromMinutes(5));
                }
            }
        }

        public void Dispose()
        {
            _sub?.Dispose();
        }
    }
}
